<?php
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class WeixinController extends BaseController {
	public $accessTokenArray;
	/**
	 * 
	 * @var Weixinhelper
	 */
	protected $iWeixin;

	public function __construct()
	{
		$this->iWeixin = new WeixinHelper();
		parent::__construct();
		
	}
	public function index()
	{
		echo $this->iWeixin->getUrl( '/' );
	}
	
	public function oauth()
	{
		$ref_url = html_entity_decode( Input::get('url'));
		if ( empty($ref_url)){
			$ref_url = route('index');
  		}
		
		$code = Input::get('code');
		$state = Input::get('state');
		
		$accessInfo = $this->iWeixin->oAuth($code);
		if(isset($accessInfo->errcode))
		{
			return Redirect::to( $ref_url );
		}
		
		$access_token  = $accessInfo->access_token;
		$openid  = $accessInfo->openid;		
		//没有绑定，进入绑定流程
		/*$userInfoArray = $this->$Weixin->getUserInfo($access_token,$openid);
		if(isset($userInfoArray->errcode))
		{
			return Redirect::to( $ref_url );
		}
		
		$userInfoArray = (array)$userInfoArray;*/
		
		/*
				
			$where = array(
					'openid' => $userInfoArray['openid'],
			);
				
			$data = array(
					'openid' =>$userInfoArray['openid'],
					'nickname' =>$userInfoArray['nickname'],
					'sex' =>$userInfoArray['sex'],
					'province' =>$userInfoArray['province'],
					'city' =>$userInfoArray['city'],
					'country' =>$userInfoArray['country'],
					'headimgurl' =>$userInfoArray['headimgurl'],
					'privilege' =>json_encode($userInfoArray['privilege']),
					'isfollow' => 1,
			);
				
			//查找微信用户 是否存在
			if())
			{//用户存在，更新用户数据
				
			}
			else
			{//用户不存在，添加用户数据
				
			}
		*/
		
		//重新获取微信用户数据
		
		
		//如果已经绑定，直接登录
		
		
		Session::set('wx_openid', $openid);
		$this->loginWithWeixinID($openid);
		return Redirect::to($ref_url);
	}
	
	protected function loginWithWeixinID($openid) {
		if ( Auth::guest()) {
			$user = User::where('wx_openid', $openid)->first();
			if ($user){
				Auth::login($user);
			}			
		}else{
			$user = Auth::user();
			if (!$user->wx_openid) {
				$user->wx_openid = $openid;
				$user->save();
			}
		}
	}
}